from flask import Blueprint, request, jsonify
from flask_jwt_extended import create_access_token, get_jwt_identity, jwt_required
from werkzeug.security import generate_password_hash, check_password_hash
from datetime import datetime
import re
from ..models import FileStorage

auth_bp = Blueprint('auth', __name__)
users = FileStorage('users.json')

def validate_password(password):
    """验证密码强度：必须包含大小写字母、数字和特殊字符"""
    if len(password) < 8:
        return False, "密码长度至少为8位"
    if not re.search(r"[A-Z]", password):
        return False, "密码必须包含大写字母"
    if not re.search(r"[a-z]", password):
        return False, "密码必须包含小写字母"
    if not re.search(r"\d", password):
        return False, "密码必须包含数字"
    if not re.search(r"[!@#$%^&*(),.?\":{}|<>]", password):
        return False, "密码必须包含特殊字符"
    return True, ""

def validate_email(email):
    """验证邮箱格式"""
    pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
    return bool(re.match(pattern, email))

def validate_phone(phone):
    """验证手机号格式"""
    pattern = r'^1[3-9]\d{9}$'
    return bool(re.match(pattern, phone))

@auth_bp.route('/register', methods=['POST'])
def register():
    try:
        data = request.get_json()
        username = data.get('username', '').strip()
        password = data.get('password', '')
        email = data.get('email', '').strip()
        phone = data.get('phone', '').strip()
        
        # 验证必填字段
        if not all([username, password, email, phone]):
            return jsonify({
                'code': 400,
                'message': '所有字段都是必填的'
            }), 400
        
        # 验证用户名长度
        if len(username) < 3 or len(username) > 20:
            return jsonify({
                'code': 400,
                'message': '用户名长度必须在3到20个字符之间'
            }), 400
        
        # 验证密码强度
        is_valid_password, password_message = validate_password(password)
        if not is_valid_password:
            return jsonify({
                'code': 400,
                'message': password_message
            }), 400
        
        # 验证邮箱格式
        if not validate_email(email):
            return jsonify({
                'code': 400,
                'message': '邮箱格式不正确'
            }), 400
        
        # 验证手机号格式
        if not validate_phone(phone):
            return jsonify({
                'code': 400,
                'message': '手机号格式不正确'
            }), 400
        
        # 检查用户名是否已存在
        if users.find_one('username', username):
            return jsonify({
                'code': 409,
                'message': '用户名已存在'
            }), 409
        
        # 检查邮箱是否已存在
        if users.find_one('email', email):
            return jsonify({
                'code': 409,
                'message': '该邮箱已被注册'
            }), 409
        
        # 检查手机号是否已存在
        if users.find_one('phone', phone):
            return jsonify({
                'code': 409,
                'message': '该手机号已被注册'
            }), 409
        
        # 创建新用户
        user = {
            'username': username,
            'password': generate_password_hash(password),
            'email': email,
            'phone': phone,
            'dark_mode': False,
            'created_at': datetime.now().isoformat()
        }
        users.insert(user)
        
        return jsonify({
            'code': 201,
            'message': '注册成功'
        }), 201
        
    except Exception as e:
        return jsonify({
            'code': 500,
            'message': f'服务器错误：{str(e)}'
        }), 500

@auth_bp.route('/login', methods=['POST'])
def login():
    try:
        data = request.get_json()
        username = data.get('username', '').strip()
        password = data.get('password', '')
        
        if not username or not password:
            return jsonify({
                'code': 400,
                'message': '用户名和密码都是必填的'
            }), 400
        
        user = users.find_one('username', username)
        if not user or not check_password_hash(user['password'], password):
            return jsonify({
                'code': 401,
                'message': '用户名或密码错误'
            }), 401
        
        # 生成访问令牌
        token = create_access_token(
            identity=username,
            additional_claims={'email': user['email']}
        )
        
        return jsonify({
            'code': 200,
            'token': token,
            'dark_mode': user.get('dark_mode', False)
        })
        
    except Exception as e:
        return jsonify({
            'code': 500,
            'message': f'服务器错误：{str(e)}'
        }), 500

@auth_bp.route('/me', methods=['GET'])
@jwt_required()
def get_current_user():
    try:
        current_user = get_jwt_identity()
        user = users.find_one('username', current_user)
        
        if not user:
            return jsonify({
                'code': 404,
                'message': '用户不存在'
            }), 404
            
        return jsonify({
            'code': 200,
            'data': {
                'username': user['username'],
                'email': user['email'],
                'phone': user['phone'],
                'dark_mode': user.get('dark_mode', False)
            }
        })
        
    except Exception as e:
        return jsonify({
            'code': 500,
            'message': f'服务器错误：{str(e)}'
        }), 500